package lei.j_java泛型_匿名内部类_反射.反射;

/**
 * @className: ReflectionExample
 * @author: xl
 * @date: 2025/3/1 16:14
 * @Version: 1.0
 * @description:
 */

import java.lang.reflect.Constructor;

class Person {
    private String name;
    private int age;

    public Person() {
        this.name = "xl";
        this.age = 0;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class Reflection创建对象Example {
    public static void main(String[] args) throws Exception {
        // 获取 Class 对象
        Class<?> clazz = Class.forName("lei.j_java泛型_匿名内部类_反射.反射.Person");

        // 使用无参构造方法创建对象
        Constructor<?> constructor1 = clazz.getConstructor();
        Person person1 = (Person) constructor1.newInstance();
        System.out.println(person1); // 输出: Person{name='Unknown'}

        // 使用带参构造方法创建对象
        Constructor<?> constructor2 = clazz.getConstructor(String.class,int.class);
        Person person2 = (Person) constructor2.newInstance("Alice",10);
        System.out.println(person2); // 输出: Person{name='Alice'}
    }
}
